import os
from threading import Thread
from gobject import idle_add
from image import Image
from symbide import PATHS
from symbide.src.widgets import WAIT_ANIMATION
from symbide.src.utils import createUniquePath

LATEX_HEADER = '\\documentclass{article}\\usepackage{fullpage}\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsfonts}\\usepackage{graphicx}\usepackage{pstricks}\pagestyle{empty}\n'


class LatexWidget(Image):
    def __init__(self, DOM):
        Image.__init__(self, show=False)
        self.image.set_from_animation(WAIT_ANIMATION)
        
        self.path = createUniquePath(PATHS['temp_pictures'], 'latex')
        self.DOM = DOM
        self.DOM.setAttribute('path', self.path)
        self.path_base = os.path.splitext(self.path)[0]
        
        self.menuitems.append(('get Latex-expression', self.getLatex))
        
        thread = Thread(target=self.createLatex)
        thread.setDaemon(True)
        thread.setName('LatexImage')
        thread.start() 
        
    def createLatex(self):
        f = open('%s.tex'%self.path_base, 'w')
        f.write(LATEX_HEADER)
        f.write('\\begin{document}\n')
        f.write(self.DOM.childNodes[0].nodeValue)
        f.write('\\end{document}\n')
        f.close()

        latex = 'latex -output-directory %s \\\\nonstopmode \\\\input{%s.tex} >%s.log'%(PATHS['temp_pictures'], self.path_base, self.path_base)
        dvi = 'dvips -o %s.ps -q %s.dvi'%(self.path_base, self.path_base)
        convert_transparent = 'convert -transparent "#ffffff" -density 150x150 -trim %s.ps %s.png'%(self.path_base, self.path_base)
        self.path = self.path_base+'_symbide.png'
        convert_white = 'convert -density 150x150 -trim %s.ps %s'%(self.path_base, self.path)

        os.system(latex)
        os.system(dvi)
        os.system(convert_transparent)
        os.system(convert_white)
        self.showImage()
        
        
    def showImage(self):
        '''
        Gives the main-thread the command to show the image.
        '''
        
        idle_add(Image.showImage, self)
        
    def getLatex(self, *args):
        clipboard = self.get_clipboard('CLIPBOARD')
        clipboard.set_text(self.DOM.childNodes[0].nodeValue)